import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;


/*
 * In this class is programmed:
 * the connection to the database
 * the saving of the data 
 */
public class MyDBSaver{
	private Connection con;
	private Long lastPrintOut = System.currentTimeMillis();
	private int counter = 0;
	
	public MyDBSaver(){
		connect();
	}
	
	public void connect(){
	    try {
	      Class.forName("com.mysql.jdbc.Driver");
	      con = DriverManager.getConnection("jdbc:mysql:///unwdmi","root", "");
	    } catch(SQLException e){
	    	e.printStackTrace();
//	    } catch (InstantiationException e) {			
//			e.printStackTrace();
//		} catch (IllegalAccessException e) {		
//			e.printStackTrace();
		} catch (ClassNotFoundException e) {	
			e.printStackTrace();
		}	    

	}
	
	public void save(Data data){
		String query= "INSERT INTO weather_data VALUES ('0', ";
		query += data.getStn() + ", ";
		query+= "'" +data.getDate()+ "', ";
		query+= "'" +data.getTime() + "', ";
		query+= data.getTemp() + ", ";
		query+= data.getDewp() + ", ";
		query+= data.getStp() + ", ";
		query+= data.getSlp() + ", ";
		query+= data.getVisib() + ", ";
		query+= data.getWdsp() + ", ";
		query+= data.getPrcp() + ", ";
		query+= data.getSndp() + ", ";
		query+= data.getFrshtt() + ", ";
		query+= data.getCldc() + ", ";
		query+= data.getWnddir();		
		query += ")";		
				
		try {			
			Statement statement = con.createStatement();
			statement.execute(query);
			counter++;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (System.currentTimeMillis() > ( lastPrintOut + 10000 )) {
			System.out.println("Writes per second: " + (counter/10));
			counter = 0;
			lastPrintOut = System.currentTimeMillis();
		}
		
	}
	
	public ArrayList<Double> getHistory(String column, int stn){
		
		ArrayList<Double> list = new ArrayList<Double>();
		
		String query = "SELECT " + column + " FROM weather_data WHERE stn = "+ stn +" ORDER BY id DESC LIMIT 30";		
	
		try{
			Statement statement = con.createStatement();
			synchronized(this){
				statement.executeQuery(query);
			}
			ResultSet result = statement.getResultSet();				
			while(result.next()){
				list.add(result.getDouble(1));
				//System.out.println(result.getObject(1));
			}		
			
		} catch(Exception e){
			e.printStackTrace();
		}
		return list;		
	}
	

}